package top.revery.task.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import top.revery.api.entity.task.BaseCompetePrice;
import top.revery.task.dto.CompetePriceDto;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;

/**
 * @author denghao
 * @title
 * @package
 * @date 2020/1/16 23:37
 */
@Service
public class CompeteService {
    @Autowired
    private CompetePriceDto competePriceDto;

    public Page<BaseCompetePrice> findPage(int pageNum, int pageSize, Map map) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "price");
        Specification<BaseCompetePrice> specification = createSpecification(map);
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(order));
        return competePriceDto.findAll(specification, pageRequest);
    }

    private Specification<BaseCompetePrice> createSpecification(Map map) {
        return new Specification<BaseCompetePrice>() {
            @Override
            public Predicate toPredicate(Root<BaseCompetePrice> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                //id
                if (map.get("id") != null && !"".equals(map.get("id"))) {
                    predicate.getExpressions().add(cb.equal(root.get("id"), map.get("id")));
                }
                //任务id
                if (map.get("taskId") != null && !"".equals(map.get("taskId"))) {
                    predicate.getExpressions().add(cb.equal(root.get("taskId"), map.get("taskId")));
                }
                if (map.get("status") != null && !"".equals(map.get("status"))) {
                    predicate.getExpressions().add(cb.equal(root.get("status"), map.get("status")));
                }
                if (map.get("keyWord") != null && !"".equals(map.get("keyWord"))) {
                    predicate.getExpressions().add(cb.equal(root.get("keyWord"), map.get("keyWord")));
                }
                return predicate;
            }
        };

    }
}
